package com.example.smartcs.config;

import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentSplitter;
import dev.langchain4j.data.document.splitter.DocumentSplitters;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.embedding.AllMiniLmL6V2EmbeddingModel;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Configuration
public class KnowledgeBaseConfig {

    private static final int MAX_DOCUMENTS = 100;

    @Bean
    public DocumentSplitter documentSplitter() {
        return DocumentSplitters.recursive(300, 0);
    }

    /**
     * 使用 AllMiniLmL6V2EmbeddingModel 作为默认的 Embedding 模型
     */
    @Bean
    @Primary
    public EmbeddingModel embeddingModel() {
        return new AllMiniLmL6V2EmbeddingModel();
    }

    @Bean
    @Primary
    public EmbeddingStore<TextSegment> embeddingStore() {
        return new InMemoryEmbeddingStore<>();
    }

    @Bean
    public MessageWindowChatMemory chatMemory() {
        return MessageWindowChatMemory.builder()
                .maxMessages(10)
                .build();
    }

    /**
     * 加载知识库文档
     */
    public Document loadDocument(String filePath) {
        try {
            Path path = Paths.get(filePath);
            String content = Files.readString(path);
            return new Document(content);
        } catch (IOException e) {
            throw new RuntimeException("无法加载文档: " + filePath, e);
        }
    }
} 